# -*- coding: utf-8 -*-
# @Time   : 2023/9/14 10:56
# @Author : 大龙 🚀
# @File   : qinghai_illegal.py
import math
import re

from apps.tax_illegal.tax_illegal.items import NetTaxIllegalProItem
from apps.tax_illegal.tax_illegal.spiders import BaseTaxIllegalSpider
from utils.tools import urlencode, parse_url_params


class QinghaiIllegalSpider(BaseTaxIllegalSpider):
    name = "qinghai_illegal"
    province: str = "青海省"
    url: str = "http://qinghai.chinatax.gov.cn/web/zdsswfsxaj/zdaj.shtml"

    def start_requests(self):
        yield from self.etax_search(**{"etax_url": "https://etax.qinghai.chinatax.gov.cn:8443"})
        url = "http://qinghai.chinatax.gov.cn/common/search/6279081b27f8406ea6bc8fdd3e5257bc"
        params = {
            "_isAgg": "false",
            "_isJson": "true",
            "_pageSize": "20",
            "_template": "index",
            "_rangeTimeGte": "",
            "_rangeTimeLt": "",
            "_channelName": "",
            "page": "1",
        }
        yield self.Request(url + "?" + urlencode(params), callback=self.parse_list)

    def parse_list(self, response, **kwargs):
        root_url, params = parse_url_params(response.request.url)
        yield from self.parse(response, **kwargs)  # 第一页解析
        total = response.json()["data"]["total"]  # 翻页
        if total and total > 10:
            pages = math.ceil(int(total) / 10)
            for page in range(2, int(pages) + 1):
                yield self.Request(root_url + "?" + urlencode({**params, "page": str(page)}), callback=self.parse)

    def parse(self, response, **kwargs):
        meta_list = response.json()["data"]["results"]
        for meta in meta_list:
            url = meta["url"]
            yield self.Request(url, callback=self.parse_detail)

    def parse_detail(self, response, **kwargs):
        item = NetTaxIllegalProItem()
        item.province = self.province

        info = []
        for i in response.xpath('//table[@class="zdaj"]//tr'):
            res = [i.xpath("string(.)").get().strip() for i in i.xpath(".//td")]
            if res:
                if len(res) != 2:
                    continue
                info.append(res)

        for k, *v in info:
            v = " ".join(v)
            k = re.sub(r"[^\u4e00-\u9fa5]+", "", k)
            if "纳税人名称" in k:
                v = re.sub(r"(<!--.*?-->|<.*?>|\s*)", "", v, flags=re.S)
                item.company_name = v
            if "纳税人识别号" in k:
                v = re.sub(r"(<!--.*?-->|<.*?>|\s*)", "", v, flags=re.S)
                item.taxpayer_id = v
            if "组织机构代码" in k:
                v = re.sub(r"(<!--.*?-->|<.*?>|\s*)", "", v, flags=re.S)
                item.org_code = v
            if "注册地址" in k:
                v = re.sub(r"(<!--.*?-->|<.*?>|\s*)", "", v, flags=re.S)
                item.city = item.resolve_register_address(v)[0]
                item.country = item.resolve_register_address(v)[1]
                item.address = v
            if "法定代表人或者负责人姓名性别及身份证号码" in k:
                v = re.sub(r"(<!--.*?-->|<.*?>|\s*)(、、.*?：)", "", v, flags=re.S)
                item.legal_representative = v
            if "违法期间法人代表或者负责人姓名性别及身份证号码":
                v = re.sub(r"(<!--.*?-->|<.*?>|\s*)", "", v, flags=re.S)
                item.illegal_legal_representative = v
            if "负有直接责任的中介机构信息" in k:
                v = " ".join(re.sub(r"(<!--.*?-->|<.*?>)", "", v, flags=re.S).split()).replace("null", "")
                item.resp_intermediary = v
            if "负有直接责任的财务人员姓名性别及身份证号码" in k:
                v = " ".join(re.sub(r"(<!--.*?-->|<.*?>)", "", v, flags=re.S).split())
                item.resp_financial = v
            if "实际负责人姓名性别及身份证号码" in k:
                v = " ".join(re.sub(r"(<!--.*?-->|<.*?>)", "", v, flags=re.S).split())
                item.resp_person = v
            if "案件性质" in k:
                item.illegal_status = v
            if "主要违法事实" in k:
                v = re.sub(r"(<!--.*?-->|\s*|<.*?>)", "", v, flags=re.S)
                illegal_facts_src = re.sub(r"(<.*?>|\s*|“|”)", "", re.sub(r"(<!--.*?-->)", "", v))
                item.illegal_facts = illegal_facts_src
            if "相关法律依据及税务处理处罚情况" in k:
                v = " ".join(re.sub(r"(<!--.*?-->|<.*?>)", "", v, flags=re.S).split())
                item.basis_and_punishment = v
        pub_date = response.xpath('//*[@name="PubDate"]/@content').get()
        item.year = pub_date[:10].replace("-", "")
        yield item


if __name__ == "__main__":

    from scrapy import cmdline

    cmdline.execute(argv=["scrapy", "crawl", "qinghai_illegal"])
